package com.esir.harmony.bus;

import java.util.HashMap;
import java.util.Map;


/**
 * [L0]消息总线Bus负责模块间通信 使用LiveData制作的
 * // 注册订阅<br />
 * LiveBus<br />
 * &nbsp; .with("key_test", String.class)<br />
 * &nbsp; .observe(this, new Observer&lt;String&gt;() {<br />
 * &nbsp;<br />
 * &nbsp; @Override public void onChanged(@Nullable String s) {<br />
 * &nbsp; }<br />
 * &nbsp; });<br />
 * &nbsp;&nbsp;<br />
 * // 发送订阅<br />
 * LiveDataBus.with("key_test").setValue("value");<br />
 * Created by 黄嵘才(HuangRc) on 2020/3/14.
 */
public final class LiveBus {
    private final Map<Object, MutableLiveData<Object>> bus;

    private LiveBus() {
        bus = new HashMap<>();
    }

    private static class SingletonHolder {
        private static final LiveBus DEFAULT_BUS = new LiveBus();
    }

    private static LiveBus get() {
        return SingletonHolder.DEFAULT_BUS;
    }

    public static MutableLiveData<Object> with(Object key) {
        return with(key, Object.class);
    }

    public static <T> MutableLiveData<T> with(Object key, Class<T> type) {
        if (!get().bus.containsKey(key)) {
            get().bus.put(key, new BusMutableLiveData<>());
        }
        return (MutableLiveData<T>) get().bus.get(key);
    }

    private static class BusMutableLiveData<T> extends LiveData<T> {

        @Override
        public void postValue(T value) {

        }

        @Override
        public void setValue(T value) {

        }
    }
}
